package com.gym.code.generator.fmt;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.gym.code.generator.fmt.model.FmtFieldModel;

import freemarker.template.Template;

/**
 * 
 * @author xinchun.wang
 * @email: 532002108@qq.com
 * @createTime 2015-4-17 下午4:53:21
 */
public class FreemarkerUtil {

	private static FreeMarkerConfigurer  freeMarkerConfigurer = new FreeMarkerConfigurer();
	static {
		try{
			freeMarkerConfigurer.setTemplateLoaderPath("classpath:fmt");
			Map<String,Object> variables= new HashMap<String,Object>();
			variables.put("template_update_delay", "1800");
			variables.put("default_encoding", "UTF-8");
			variables.put("locale", "zh_CN");
			freeMarkerConfigurer.setFreemarkerVariables(variables);
			freeMarkerConfigurer.afterPropertiesSet();
		}catch(Exception e){
			
		}
	}

	public  static  String formatTemplate(Map<String, Object> dataModel, String templateName) {
		String htmlText = null;
		try {
			Template tpl =freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
			htmlText =  FreeMarkerTemplateUtils.processTemplateIntoString(tpl, dataModel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return htmlText;
	}

	public  static String formatDaoSelectOneBeanTemplate(String beanName, String sql, List<FmtFieldModel> resultList, String params) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("beanName", beanName);
		map.put("resultList", resultList);
		map.put("sql", sql);
		map.put("params", params);
		return formatTemplate(map, "dao-select-one-bean.fmt");
	}

	public  static  String formatDaoSelectListBeanTemplate(String beanName, String sql, List<FmtFieldModel> resultList, String params) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("beanName", beanName);
		map.put("resultList", resultList);
		map.put("sql", sql);
		map.put("params", params);
		return formatTemplate(map, "dao-select-list-bean.fmt");
	}

	public static String formatDaoTemplate(String sql, String params) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sql", sql);
		map.put("params", params);
		return formatTemplate(map, "dao-update.fmt");
	}
	
	
	public static String formatEnumInstanceTemplate(String enumType) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("EnumType", enumType);
		return formatTemplate(map, "enum-instance.fmt");
	}

}
